﻿using MediumApi.Db;
using MediumApi.Result;
using MediumApi.Service;
using MediumApi.Tools;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection.PortableExecutable;
using System.Threading.Channels;
using System.Threading.Tasks;
using static MediumApi.Param.AppParam;
using static MediumApi.Result.AppResult;
using static System.Net.Mime.MediaTypeNames;
using Channel = MediumApi.Db.Channel;

namespace MediumApi.Controllers
{
    /// <summary>
    /// app控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class AppController : BaseController
    {
        private readonly AppService _appService;
        private readonly ConsoleService _consoleService;
        private readonly string _tempFolder;
        public AppController(AppService appService, ConsoleService consoleService, IWebHostEnvironment env)
        {
            _appService = appService;
            _consoleService = consoleService;
            _tempFolder = Path.Combine(env.ContentRootPath, "Temp");
            Directory.CreateDirectory(_tempFolder);
        }
        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<OperateResult> GetCode(string PhoneNumber)
        {
            if (await _appService.SendCode(PhoneNumber) > 0) return Success();
            return Error();
        }
        /// <summary>
        /// 校验验证码
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<OperateResult> CAPTCHACode(CAPTCHACodeParam param)
        {
            if (await _appService.CAPTCHACode(param) > 0) return Success();
            return Error();
        }
        /// <summary>
        /// App登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<OperateResult> AppLogin(AppLoginParam param)
        {

            var data = await _appService.AppLogin(param);
            if (data == null) return Error();
            var token = TokenHelpers.GetTicketWithCache((string)data.Id, 0);
            bool IsTourist = false;
            if (string.IsNullOrEmpty(param.PhoneNumber))
            {
                IsTourist = true;

            }
            return Success(new { Token = token, UserId = data.Id, PhoneNumber = data.PhoneNumber, Name = data.Name, AvatarUrl = data.AvatarUrl, IsTourist = IsTourist });
        }

        ///<summary>
        /// 查询频道列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(PagedResult<List<SelectAppChannelListResult>>))]
        public async Task<OperateResult> SelectAppChannelList(int Type)
        {
            return Success(_appService.SelectChannelList(Type));
        }
        ///<summary>
        /// 查询单频道
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(SelectAppChannelListResult))]
        public async Task<OperateResult> SelectAppChannel(int Id)
        {
            return Success(_appService.SelectChannel(Id));
        }
        ///<summary>
        /// 查询帖子列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(List<SelectAppContentsListResult>))]
        public async Task<OperateResult> SelectAppContentsList(SelectAppContentsListParam param)
        {
            if (string.IsNullOrEmpty(this.UserID))
            {
                param.UserId = "1";
            }
            else
            {
                param.UserId = this.UserID;
            }

            return Success(await _appService.SelectAppContentsList(param));
        }
        ///<summary>
        /// 查询单个帖子
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(List<SelectAppContentsListResult>))]
        public async Task<OperateResult> SelectAppContents(string Id)
        {
            string UserId = "";
            if (string.IsNullOrEmpty(this.UserID))
            {
                UserId = "1";
            }
            else
            {
                UserId = this.UserID;
            }
            await _appService.AddContentsSrecord(new AddContentsSrecordParma
            {
                UserId = UserId,
                ContentsId = Id,
                Type = 1
            });
            return Success(await _appService.SelectAppContents(Id, UserId));
        }
        ///<summary>
        /// 添加评论
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<OperateResult> AddComments(AddCommentsParam param)
        {
            if (!string.IsNullOrEmpty(this.UserID)) param.UserId = this.UserID;
            if (await _appService.AddComments(param) > 0) return Success();
            return Error();
        }
        ///<summary>
        /// 删除评论
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<OperateResult> DelComments(string Id)
        {
            if (await _appService.DelComments(Id) > 0) return Success();
            return Error();
        }
        ///<summary>
        /// 查询评论列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(List<SelectCommentsListResult>))]
        public async Task<OperateResult> SelectCommentsList(string Id)
        {
            return Success(await _appService.SelectCommentsList(Id));
        }
        ///<summary>
        /// 查询用户评论
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ApiAuthority]
        [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(PagedResult<List<SelectCommentsListResult>>))]
        public async Task<OperateResult> SelectUserCommentsList(SelectUserCommentsListParam param)
        {
            param.UserId = this.UserID;
            return Success(await _appService.SelectUserCommentsList(param));
        }
        ///<summary>
        /// 添加点赞/历史
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<OperateResult> AddContentsSrecord(AddContentsSrecordParma param)
        {
            param.UserId += this.UserID;
            if (await _appService.AddContentsSrecord(param) > 0) return Success();
            return Error();
        }
        ///<summary>
        /// 删除点赞/历史
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<OperateResult> DelContentsSrecord(string Id, int Type)
        {
            string UserId = "";
            if (string.IsNullOrEmpty(this.UserID))
            {
                UserId = "1";
            }
            else
            {
                UserId = this.UserID;
            }
            await _appService.DelContentsSrecord(Id, UserId, Type); return Success();
            return Error();
        }
        ///<summary>
        /// 查询点赞/历史列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ApiAuthority]
        [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(PagedResult<List<SelectAppContentsListResult>>))]
        public async Task<OperateResult> SelectContentsSrecordList(SelectContentsSrecordListParam param)
        {
            param.UserId = this.UserID;
            return Success(await _appService.SelectContentsSrecordList(param));
        }
        ///<summary>
        /// 添加关注
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ApiAuthority]
        public async Task<OperateResult> AddConcern(string ConcernUserId)
        {
            AddConcernParam param = new AddConcernParam()
            {
                UserId = this.UserID,
                ConcernUserId = ConcernUserId
            };
            if (await _appService.AddConcern(param) > 0) return Success();
            return Error();
        }
        ///<summary>
        /// 取消关注
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ApiAuthority]
        public async Task<OperateResult> DelConcern(string ConcernUserId)
        {
            AddConcernParam param = new AddConcernParam()
            {
                UserId = this.UserID,
                ConcernUserId = ConcernUserId
            };
            if (await _appService.DelConcern(param) > 0) return Success();
            return Error();
        }
        /// <summary>
        /// 测试
        /// </summary>
        /// <param name="videoFile"></param>
        /// <returns></returns>
        [HttpPost("extract-thumbnail")]
        public async Task<IActionResult> ExtractThumbnail(IFormFile videoFile)
        {
            try
            {
                // 1. 验证输入
                if (videoFile == null || videoFile.Length == 0)
                    return BadRequest("No file uploaded");

                if (!videoFile.FileName.EndsWith(".mp4", StringComparison.OrdinalIgnoreCase))
                    return BadRequest("Only MP4 files are supported");

                // 2. 生成唯一文件名
                var uniqueId = Guid.NewGuid().ToString();
                var videoPath = Path.Combine(_tempFolder, $"{uniqueId}.mp4");
                var thumbnailPath = Path.Combine(_tempFolder, $"{uniqueId}.jpg");

                try
                {
                    // 3. 保存上传文件
                    await using (var stream = new FileStream(videoPath, FileMode.Create))
                    {
                        await videoFile.CopyToAsync(stream);
                    }

                    // 4. 调用FFmpeg提取缩略图
                    var ffmpegProcess = new Process
                    {
                        StartInfo = new ProcessStartInfo
                        {
                            FileName = "ffmpeg",
                            Arguments = $"-i \"{videoPath}\" -ss 00:00:00.000 -vframes 1 -q:v 2 \"{thumbnailPath}\"",
                            RedirectStandardOutput = true,
                            RedirectStandardError = true,
                            UseShellExecute = false,
                            CreateNoWindow = true
                        }
                    };

                    ffmpegProcess.Start();
                    var errorOutput = await ffmpegProcess.StandardError.ReadToEndAsync();
                    await ffmpegProcess.WaitForExitAsync();

                    if (ffmpegProcess.ExitCode != 0)
                    {
                        //_logger.LogError($"FFmpeg error: {errorOutput}");
                        throw new Exception($"FFmpeg processing failed: {errorOutput}");
                    }

                    // 5. 验证输出文件
                    if (!System.IO.File.Exists(thumbnailPath) || new FileInfo(thumbnailPath).Length == 0)
                        throw new Exception("Generated thumbnail is empty or missing");

                    // 6. 返回结果
                    var thumbnailBytes = await System.IO.File.ReadAllBytesAsync(thumbnailPath);
                    return File(thumbnailBytes, "image/jpeg", $"{Path.GetFileNameWithoutExtension(videoFile.FileName)}.jpg");
                }
                finally
                {
                    // 7. 清理临时文件
                    CleanupTempFile(videoPath);
                    CleanupTempFile(thumbnailPath);
                }
            }
            catch (Exception ex)
            {
                //_logger.LogError(ex, "Error processing video thumbnail");
                return StatusCode(500, $"Error processing video: {ex.Message}");
            }
        }

        private void CleanupTempFile(string path)
        {
            try
            {
                if (System.IO.File.Exists(path))
                    System.IO.File.Delete(path);
            }
            catch (Exception ex)
            {
                //_logger.LogWarning(ex, $"Failed to delete temp file: {path}");
            }
        }
    }
}
